
'use strict';
// loadRemoteTemplate()


const { promisify } = require('util');
const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const figlet = promisify(require('figlet'));
const clear = require('clear');
const Inquirer = require('inquirer');
const validatePackageName = require('validate-npm-package-name');

const Creator = require('./Creator');

module.exports = async (projectName = 'my-project') => {
  // 清空屏幕
  clear();

  // 输出欢迎界面
  const welcome = await figlet('OCE WELCOME')
  console.log(`${chalk.green(welcome)}\n`);

  const cwd = process.cwd()
  const targetDir = path.resolve(cwd, projectName || '.')

  // 判断项目名称是否合法
  const { validForNewPackages, errors, warnings } = validatePackageName(projectName);

  // 如果所输入的不是合法npm包名，则退出
  if (!validForNewPackages) {
    console.log(chalk.red(`不合法的项目名: '${projectName}'\n`))

    errors && errors.forEach(err => {
      console.log(chalk.red.dim(`❌ ${err}\n`))
    })

    warnings && warnings.forEach(warn => {
      console.log(chalk.red.dim(`⚠️ ${warn}\n`))
    })
    process.exit();
  }

  if (fs.existsSync(projectName)) {
    const { action } = await Inquirer.prompt([
      {
        name: 'action',
        type: 'list',
        message: `目标文件夹 ${chalk.cyan(projectName)} 已经存在，请选择：`,
        choices: [
          { name: '覆盖', value: 'overwrite' },
          { name: '取消', value: false }
        ]
      }
    ])
    if (!action) {
      return
    }
    if (action === 'overwrite') {
      console.log(`\nRemoving ${chalk.cyan(projectName)}...\n`)
      await fs.remove(projectName)
    }
  }

  const creator = new Creator(projectName, targetDir);

  await creator.create()
}
